package com.bxji.spring.ms.provider.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bxji.spring.ms.commons.domain.User;
import com.bxji.spring.ms.provider.service.MyTestService;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class UserController {

    @Autowired
    private EurekaClient eurekaClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private MyTestService myTestService;

    @RequestMapping("/myinfo")
    @HystrixCommand(fallbackMethod = "myerror")
    public String info(HttpServletRequest request) throws InterruptedException {
        int time = RandomUtils.nextInt(2800);
        System.out.println("休眠毫秒: " + time);
        Thread.sleep(time);
        String message = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getServletPath();
        return message;
    }

    public String myerror(HttpServletRequest request) {
        String message = "网络繁忙，请稍后再试-_-。PS：服务消费者自己提供的信息";
        return message;
    }

    @GetMapping("/getUser/{id}")
    public User findById(@PathVariable Long id) {
        User user = myTestService.getUser(id, "张三_" + id, id.intValue() / 3);
        System.out.println(String.format("获取用户：ID {%d}，姓名 {%s},年龄 {%d}", user.getId(), user.getName(), user.getAge()));
        return user;
    }

    // 获取服务提供的ip
    @GetMapping("/eureka-instance/{serverName}")
    public String serviceUrl(@PathVariable String serverName) {
        InstanceInfo instance = this.eurekaClient.getNextServerFromEureka(serverName, false);
        return instance.getHomePageUrl();
    }

    // 获取服务提供者信息
    @GetMapping("/instance-info")
    public ServiceInstance showInfo() {
        ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
        return localServiceInstance;
    }

}
